package com.vhall.component.service.account.impl;


import com.vhall.component.framework.common.exception.BusinessException;
import com.vhall.component.plugin.common.constant.RedisKey;
import com.vhall.component.plugin.common.exception.BizErrorCode;
import com.vhall.component.plugin.common.utils.RandomUtil;
import com.vhall.component.service.account.CodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


/**
 * @author dalong
 * @date 2021-04-28 11:19
 */
@Service
public class CodeServiceImpl implements CodeService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private MwGateMsgServiceImpl mwGateMsgService;

    @Override
    public boolean checkCode(String phone, Integer code) {
        String cacheKey = String.format("%s%s", RedisKey.CODE_KEY, phone);
        String cacheCode = redisTemplate.opsForValue().get(cacheKey);
        if (cacheCode == null || !Integer.valueOf(cacheCode).equals(code)) {
            return false;
        }
        // 删除缓存
        redisTemplate.delete(cacheKey);
        String intervalKey = String.format("%s%s", RedisKey.INTERVAL_KEY, phone);
        redisTemplate.delete(intervalKey);
        return true;
    }

    @Override
    public boolean send(String phone, Integer expires, Integer interval) {
        // 一分钟重复发送校验
        String cacheKeyInterval = String.format("%s%s", RedisKey.INTERVAL_KEY, phone);
        //加锁校验
        if (!redisTemplate.opsForValue().setIfAbsent(cacheKeyInterval, "true", interval, TimeUnit.SECONDS)) {
            throw new BusinessException(BizErrorCode.COMP_SMS_THRESHOLD_WARING);
        }

        // 生成验证码
        Integer code = RandomUtil.getRandomNum(100000, 999999);

        // 设置验证码缓存
        String cacheKey = String.format("%s%s", RedisKey.CODE_KEY, phone);
        redisTemplate.opsForValue().set(cacheKey, code.toString(), expires, TimeUnit.SECONDS);

        String msgContent = "尊敬的用户:您的验证码为" + code + ", 本验证码3分钟有效, 感谢使用";
        return mwGateMsgService.send(phone, msgContent, true);
    }
}

